import { Component, OnInit ,ElementRef,Renderer2 } from '@angular/core';
import { FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms';
import { HttpClient } from '@angular/common/http';
import { NzModalService } from 'ng-zorro-antd/modal';
import { Router } from '@angular/router';

// import * as bankValid from '../../../../../../assets/js/bankValid';

// import { CustValidators } from './CustValidators';
import { BankTransferService } from 'src/app/service/business/bank-transfer.service';
import { MessageService } from 'src/app/service/message.service';
import { UserBindService } from 'src/app/service/user-bind.service';
import { PHONE_REG } from 'src/app/utils/regExp';

// declare let pdfjsLib: any;
@Component({
  selector: 'app-bank-message-confirm',
  templateUrl: './bank-message-confirm.component.html',
  styleUrls: ['./bank-message-confirm.component.scss']
})
export class BankMessageConfirmComponent implements OnInit {
  nzFilterOption:any; //zy
  acceptNo: string = '';

  validateForm: FormGroup = new FormGroup({
    id: new FormControl(''),
    usageCode: new FormControl('', [
      Validators.required
    ]),
    address: new FormControl(''),
    balanceName: new FormControl(''),
    balanceProperty: new FormControl('0', [
      Validators.required
    ]),
    businessType: new FormControl('0', [ // 办理类型
      Validators.required
    ]),

    accountName: new FormControl('', [
      Validators.required
    ]),
    account: new FormControl('', [
      Validators.required
    ]), // 银行账户
    bankId: new FormControl('', [
      Validators.required
    ]),
    bankCode: new FormControl(''),
    bankName: new FormControl(''),
    contactPhone: new FormControl('', [
      Validators.required, Validators.pattern(PHONE_REG)
    ]),
    email: new FormControl(''),
    // mailAddress: new FormControl('', CustValidators.maxByteLength(100)),

    certificateNum: new FormControl('', [
      Validators.required
    ]),
    trustorName: new FormControl('', [
      Validators.required
    ]),
    trustorTel: new FormControl(''),

    // 附件
    accountPic: new FormControl(''),
    identityPic: new FormControl(''),
    
    companyPic: new FormControl(''),
    balanceAuthPic: new FormControl(''),
    businessAuthPic: new FormControl(''),

    signature: new FormControl(), // 签署信息
    infoSources: new FormControl('WT'),
    isSecret: new FormControl(true)
  });

  constructor(private fb: FormBuilder,
    public el:ElementRef,
    public renderer2:Renderer2,
    public http: HttpClient,
    private router: Router,
    private bankTransferService: BankTransferService,
    private message: MessageService,
    private userBind: UserBindService,
    // private feeCommonService:FeeCommonService

  ) {}

  ngOnInit() {
    this._initPage();
  }

  btnIsVisible = true;
  pageType = 2; // 2 新增
  pageData: any = null;
  pageTitle = '银行划扣'
  _initPage(){
    this._getBindList();

    this._getBalancePropertys();

    this.pageType = this.bankTransferService.pageType;
    this.pageData = this.bankTransferService.pageData;
    console.log(this.pageData);
    if(this.pageData !== null && this.pageType === 0){ // 预览
      this.btnIsVisible = false;
      // this.pageData.account = this.pageData.account.replace(/\s*/g,"");
      console.log(this.pageData)
      this.balanceProperty = this.pageData.balanceProperty;
      this.validateForm.patchValue(this.pageData);
      this.validateForm.disable();
      this.pageTitle = '银行划扣预览';
    }
    if(this.pageType === 1){
      // 银行账户需要先去掉空字符串
      this.pageData.account = this.pageData.account.replace(/\s*/g,"");
      this.pageTitle = '银行划扣';

      this.bankList = [{bankName: this.pageData.bankName, bankId: this.pageData.bankId}];
      
      // this._bankValid(this.pageData.account);

      this.validateForm.patchValue(this.pageData);


      // IE浏览器兼容
      setTimeout(() => {
        this.validateForm.get('account')?.markAsPristine();
        this.validateForm.get('accountName')?.markAsPristine();
      }, 500);

    }
  }
  _getBalancePropertys(){
    this.bankTransferService.getCodeItems('D042').subscribe(res => {
      
      this.balancePropertys = res.map((item: any) => {
        if(item.name === '个人'){
          item.bp = '0';
        }
        if(item.name === '单位'){
          item.bp = '1';
        }
        return item;
      });
      if(this.pageType === 2){
        this.validateForm.patchValue({
          balanceProperty: '0'
        })
      }
    })
  }

  /************************* 0830 银行划账 功能调整 *************************/
  chargeModes: any = [];
  balancePropertys: any = [];
  invoiceGetModes: any = [];
  invoicePrintModes: any = [];
  acctypes: any = [];
  reduceModes: any = [];
  _initCodeItems(){
    // this._getChargeModes('D047', 'chargeModes'); // 结算方式
    this._getChargeModes('D042', 'balancePropertys'); // 结算属性
    // this._getChargeModes('D048', 'invoiceGetModes'); // 发票获取方式
    // this._getChargeModes('D046', 'invoicePrintModes'); // 发票打印方式
    // this._getChargeModes('D050', 'acctypes'); // 账户类别
    // this._getChargeModes('D049', 'reduceModes'); // 冲抵模式
  }
  // 
  _getChargeModes(type: any, key: any){
    this.bankTransferService.getCodeItems(type).subscribe((res: any) => {
      this[key] = res;
    }, () => {
      
    })
  }

  balanceProperty = '-1';
  onBalanceProperty(e: any){
    this.setValidators()
    this.balanceProperty = e;
  }
  businessType = '0';
  onbusiTypeChange(e: any){
    this.setValidators()
    this.businessType = e;
    this.btnDisabled = false
    if(this.validateForm.get('usageCode')?.value){
      if(e === '1' && !this.hasBanktransfer){
        this.message.infoModal('当前编号无银行划扣信息，无需办理取消', () => {
          history.go(-1)
        })
      }
    }
  }
  setValidators(){
    // this.validateForm.get('identityPic').reset();
    this.validateForm.get('companyPic')?.reset();
    this.validateForm.get('balanceAuthPic')?.reset();
    this.validateForm.get('businessAuthPic')?.reset();
    this.validateForm.get('accountPic')?.reset();

    if(this.validateForm.get('balanceProperty')?.value === '0'){
      this.validateForm.get('accountPic')?.setValidators([Validators.required])
      this.validateForm.get('identityPic')?.setValidators([Validators.required])

      this.validateForm.get('companyPic')?.clearValidators()
      this.validateForm.get('balanceAuthPic')?.clearValidators()
      this.validateForm.get('businessAuthPic')?.clearValidators()

      this.validateForm.get('trustorName')?.clearValidators()
      this.validateForm.get('trustorTel')?.clearValidators()

      this.validateForm.get('email')?.setValidators([
        Validators.pattern(/^[A-Za-z\d]+([-_.][A-Za-z\d]+)*@([A-Za-z\d]+[-.])+[A-Za-z\d]{2,5}$/),
        // CustValidators.maxByteLength(40)
      ])
    }else{
      this.validateForm.get('identityPic')?.setValidators([Validators.required])
      this.validateForm.get('companyPic')?.setValidators([Validators.required])
      this.validateForm.get('balanceAuthPic')?.setValidators([Validators.required])
      this.validateForm.get('businessAuthPic')?.setValidators([Validators.required])

      this.validateForm.get('trustorName')?.setValidators([Validators.required])
      this.validateForm.get('trustorTel')?.setValidators([
        Validators.required, Validators.pattern(/^(((13[0-9]{1})|(15[0-9]{1})|(18[0-9]{1}))+\d{8})$/)
      ])

      this.validateForm.get('email')?.setValidators([
        Validators.required, 
        Validators.pattern(/^[A-Za-z\d]+([-_.][A-Za-z\d]+)*@([A-Za-z\d]+[-.])+[A-Za-z\d]{2,5}$/)
      ])

      this.validateForm.get('accountPic')?.clearValidators()
    }

    if(this.validateForm.get('businessType')?.value === '1'){
      console.log(123)
      // this.validateForm.get('accountName').clearValidators()
      this.validateForm.get('accountName')?.setValidators([Validators.required])
      this.validateForm.get('account')?.clearValidators()
      this.validateForm.get('bankId')?.clearValidators()

      this.validateForm.get('accountPic')?.clearValidators()
      this.validateForm.get('balanceAuthPic')?.clearValidators()

      this.validateForm.get('email')?.clearValidators()
    }else{
      this.validateForm.get('accountName')?.setValidators([Validators.required])
      this.validateForm.get('account')?.setValidators([Validators.required])
      this.validateForm.get('bankId')?.setValidators([Validators.required])
    }

    this.validateForm.updateValueAndValidity()
  }

  /************************* 0830 银行划账 功能调整 end *************************/

  btnLoading = false;
  onSubmit(){
    console.log(this.validateForm.getRawValue())
    if(!this._validateForm()){
      return ;
    }

    // 保存 协议
    this._savePDF();
    // let pdfID = this._savePDF();
    // if(pdfID === ''){
    //   this.util.error('保存协议PDF失败，稍后重试');
    //   return ;
    // }

    
  }
  _validateForm(){
    let flag = true;

    let controls = this.validateForm.controls;
    for (let i in controls) {
      controls[i].markAsDirty();
      controls[i].updateValueAndValidity();
    }

    console.log(controls)
    
    for(let i in controls){
      if(controls[i].invalid){
        flag = false ;
      }
    }

    return flag;
  }
  _savePDF(){
    if(!this.nameData && this.pageType === 1){
      this.btnLoading = true;
      this._submitForm(false);
    }else{
      if(!this.nameData){
        this.message.info('请签署业务办理单');
        return ;
      }
      this.btnLoading = true;
  
      this.bankTransferService.savePDF(this._getFormData()).subscribe((res: any) => {
        if(res && res.fileId){
          this._submitForm(res.fileId);
        }else{
          this.message.error('保存文件失败')
          this.btnLoading = false;
        }
      }, (error: any) => {
        this.message.error('保存文件失败')
        this.btnLoading = false;
      });
    }
    
    
  }

  _submitForm(id: any){
    if(id){
      this.validateForm.patchValue({
        signature: id
      })
    }
    let params = this.validateForm.value;
    // params.balanceProperty = this.balanceProperty;


    if(this.pageType === 2){
      this._addBankTransfer(params);
    }
    if(this.pageType === 1){
      this._updateBankTransfer(params);
    }
  }

  // 文件上传处理
  uploadBack(value: string, fieldName: string){
    this.validateForm.get(fieldName)?.setValue(value);
  }

  _addBankTransfer(params: any){
    this.bankTransferService.addBankTransfer(params).subscribe((res: any) => {
      if(res.result === 'success'){
        this.message.infoModal('新增成功', () => {
          this.router.navigate(['/me/bank-trans/list']);
        });
        this.btnLoading = false;
      }else{
        this.message.error('提交失败');
        this.btnLoading = false;
      }
      
    }, (error: any) => {
      this.btnLoading = false;
      this.message.createErrorMessage(error);
    })
  }
  _updateBankTransfer(params: any){
    this.bankTransferService.updateBankTransfer(params).subscribe((res: any) => {
      this.message.successModal('更新成功', () => {
        this.router.navigate(['/me/bank-trans/list']);
      })
      this.btnLoading = false;
    }, (error: any) => {
      this.btnLoading = false;
      this.message.createErrorMessage(error);
    })
  }

  accountOnBlur(){
    // e.preventDefault();
    // e.stopPropagation();
    // e.stopPropagation();  

    this.codeNumber = '';
    this.validateForm.get('bankId')?.reset();
    this.bankList = [];

    let accountObj = this.validateForm.get('account');   
    let cardNo = accountObj?.value;
    // cardNo = cardNo.replace(/\s*/g,"");

    // 1. 银行账户 校验
    // if(cardNo === ''){
    //   return ;
    // }
    // if (isNaN(cardNo)) {
		// 	cardNo = parseInt(cardNo);
		// 	if (isNaN(cardNo)) {
    //     accountObj.setErrors({custError: '银行卡号必须是数字'});
    //     return ;
		// 	}
		// }
		// if (cardNo.toString().length < 15 || cardNo.toString().length > 19) {
    //   accountObj.setErrors({custError: '银行卡位数必须是15到19位数字'});
    //   return ;
    // }

    // 空格隔开 银行卡号
    // this.validateForm.patchValue({
    //   account: cardNo.replace(/\s/g,'').replace(/(.{4})/g,"$1 ")
    // })

    // 2. 
    this._bankValid(cardNo);

  }
  onBlur(){
    let accountObj = this.validateForm.get('account');;

    let cardNo = (accountObj?.value || '').replace(/\s*/g,"");

    // if (isNaN(cardNo)) {
		// 	cardNo = parseInt(cardNo);
		// 	if (isNaN(cardNo)) {
    //     accountObj.setErrors({custError: '银行卡号必须是数字'});
    //     return ;
		// 	}
		// }
		// if (cardNo.toString().length < 15 || cardNo.toString().length > 19) {
    //   accountObj.setErrors({custError: '银行卡位数必须是15到19位'});
    //   return ;
    // }
    let account = cardNo.replace(/\s/g,'').replace(/(.{4})/g,"$1 ");

    this.validateForm.patchValue({
      account
    })
  }

  _bankValid(cardNo: string){
    // this.codeNumberFlag = false;
    // return bankValid.getBankBin(cardNo).then(data => {
    //   if (data && data.codeNumber) {
    //     this.codeNumber = data.codeNumber;
    //   }
    //   // this.codeNumberFlag = true;
    // }).catch(() => {
    //   // this.codeNumberFlag = true;
    //   // this.util.error('查询开户银行出错，刷新重试');
    // });
  }



  bankList: any = [];
  codeNumber = '';
  bankIsLoading = false;
  bankSearch(value: string){
    this.bankIsLoading = true;
    this.bankTransferService.getBankList(this.codeNumber, value).subscribe(res => {
      if(res){
        this.bankList = res.resultList;
      }else{
        this.bankList = [];
      }
      this.bankIsLoading = false;
    }, (error: any) => {
      console.log(error);
      this.bankIsLoading = false;
      // this.util.createErrorMessage(error);
    });
  }
  onBankChange(value: string){
    this.validateForm.patchValue({bankCode: '', bankName: ''})
    
    let bank = this.bankList.find((item: any) => {
      return item.bankId === value;
    })
    if(bank){
      this.validateForm.patchValue({ bankCode: bank.bankCode, bankName: bank.bankName })
    }
  }


  // 重置
  onReset(){
    // this.util.confirm('重置将初始化表单信息,并将返回上一页，确定重置表单吗？', () => {
    //   if(this.pageType === 2){
    //     this.validateForm.reset();
    //   }
    //   if(this.pageType === 1){
    //     this.validateForm.patchValue(this.pageData);

    //     this.bankList = [{bankName: this.pageData.bankName, bankId: this.pageData.bankId}];
    //     this.validateForm.patchValue({
    //       bankId: this.pageData.bankId
    //     })
    //     this._bankValid(this.pageData.account);
    //   }
    //   history.go(-1);
    // })
  }

  // 获取 绑定用户
  usageCodeInfo: any = [];
  usageCodeLoading = false;
  _getBindList(){  
    this.usageCodeLoading = true;
    this.userBind._getUsageCodeInfo().subscribe((res: any) => {
      this.usageCodeInfo = res;

      if(this.pageType === 0 || this.pageType === 1){
        let address = (this.usageCodeInfo.find((item: any) => {
          return item.usageCode === this.pageData.usageCode;
        }) as any)?.address;
        this.validateForm.patchValue({ address });
      }
      this.usageCodeLoading = false;
    }, (error: any) => {
      this.usageCodeLoading = false;
      // this.util.createErrorMessage(error);
      // this.usageCodeInfo = [{
      //   usageCode: '1231231231',
      //   accountName: '测试',
      //   address: '测试地址'
      // }]
    })
  }

  hasBanktransfer = false
  btnDisabled = false
  onUsageCodeChange(usageCode: string){
    this.validateForm.patchValue({
      balanceName: '',
      address: '',
    })

    this.btnDisabled = false
    this.hasBanktransfer = false

    let usageCodeItem = this.usageCodeInfo.find((item: any) => {
      return item.usageCode === usageCode;
    });
    if(usageCodeItem){
      this.validateForm.patchValue({
        balanceName: usageCodeItem.accountName,
        address: usageCodeItem.address,
      })

      this.http.get(`/api/gsxmcp/cg/um/v1.0/balance/info/${usageCode}`).subscribe((res: any) => {
        if(res && res.usageCode){
          this.hasBanktransfer = true
          this.message.confirmModal('当前用户已有银行划账信息, 请确认是否更改？', () => {
            
          }, () => {
            history.go(-1)
          })
        }else{
          this.hasBanktransfer = false
          if(this.validateForm.get('businessType')?.value === '1'){
            this.message.infoModal('当前编号无银行划扣信息，无需办理取消', () => {
              history.go(-1)
            })
          }
        }
      })
    }
  }

  onBack(){
    history.go(-1);
  }

  // 模块框用户协议
  modalIsVisible = false;
  nzSpinning = true;
  viewPDF(){
    if(this.pageType === 0 || this.pageType === 1){
      this.modalIsVisible = true;
      this.nzSpinning = true;

      let url = `/api/gsxmcp/pb/fm/v1.0/download/${this.pageData.signature}`;
      this._pdfPreview2(url);
    }else{
      if(this._viewPDFValidate()){
        this.modalIsVisible = true;
        this.nzSpinning = true;

        this._pdfjs(this._getFormData());
      }
      
    }
  }
  _viewPDFValidate(){
    let flag = true;

    let controls = this.validateForm.controls;
    for (let i in controls) {
      if(['accountPic', 'identityPic', 'companyPic', 'balanceAuthPic', 'businessAuthPic'].indexOf(i) === -1){
        controls[i].markAsDirty();
        controls[i].updateValueAndValidity();
      }
    }
    for(let i in controls){
      if(controls[i].invalid){
        flag = false ;
      }
    }

    return flag;
  }
  modalHandleCancel(){
    this.modalIsVisible = false;
  }
  modalHandleOk(){

    this.signModal()
  }


  
  _validateName(): boolean{
    let flag = true;
    if(!this.nameData && this.pageType !== 0){
      // this.util.error('签名不能为空!先保存签名');
      flag = false;
    }
    return flag;
  }
  /**
    <><><>银行划扣协议模版参数<><><>
    "fullName":"甲方付款人全称",
    "bankName":"开户行",
    "accountName":"银行账户名称",
    "account":"银行卡号",
    "code":"用水编号",
    "userName":"用户名称",
    "mobilePhone":"手机号",
    "tel":"座机号",
    "address":"用水地址",
    "img_sqrqm":"申请人签名base64图片数据",
    "year":"年",
    "month":"月",
    "day":"日"
   */
  _getFormData(): FormData{
    let formData = new FormData();
    if(this.balanceProperty === '0'){
      formData.append('yhlx', 'gryh'); // 用户类型
      formData.append('grzjhm', this.validateForm.get("certificateNum")?.value);
    }else if(this.balanceProperty === '1'){
      formData.append('yhlx', 'dwyh'); // 用户类型
      formData.append('dwzjhm', this.validateForm.get("certificateNum")?.value);
      formData.append('nsrsbh', this.validateForm.get("certificateNum")?.value);
    }
    // 用户编号
    formData.append('code', this.validateForm.get("usageCode")?.value);
    formData.append('address', this.validateForm.get("address")?.value);
    formData.append('userName', this.validateForm.get("balanceName")?.value);

    formData.append('bankName', this.validateForm.get("bankName")?.value);
    formData.append('fullName', this.validateForm.get("accountName")?.value);
    formData.append('accountName', this.validateForm.get("accountName")?.value);
    formData.append('account', this.validateForm.get("account")?.value);
    formData.append('mobilePhone', this.validateForm.get("trustorTel")?.value); // 联系手机
    formData.append('tel', this.validateForm.get("trustorTel")?.value); // 联系手机

    formData.append('img_sqrqm', this.nameData);

    formData.append('year', String(new Date().getFullYear()));
    formData.append('month', String(new Date().getMonth() + 1));
    formData.append('day', String(new Date().getDate()));

    return formData;
  }

  _pdfjs(formData: any){
    this.bankTransferService.savePDF(formData).subscribe((res: any) => {
      // var b = new Blob([res], { type: 'application/pdf;chartset=UTF-8' });
      // var fileURL = URL.createObjectURL(b);
      if(res && res.fileId){
        let url = `/api/gsxmcp/pb/fm/v1.0/download/${res.fileId}`;
        console.log(url);
  
        this._pdfPreview2(url);
      }else{
        this.nzSpinning = false;
      }
      
    }, (error: any) => {
      this.nzSpinning = false;
    })
  }

  // _pdfPreview(url){
  //   if(!url){
  //     return ;
  //   }
  //   let loadingTask = pdfjsLib.getDocument(url);

  //   loadingTask.promise.then(function(pdf) {

  //     pdf.getPage(1).then(function(page) {
  //       var scale = 1.0;
  //       var viewport = page.getViewport({ scale: scale, });
  //       var canvas = <HTMLCanvasElement> document.getElementById('pdf-canvas');
  //       var context = canvas.getContext('2d');
  //       canvas.height = viewport.height;
  //       canvas.width = viewport.width;

  //       var renderContext = {
  //         canvasContext: context,
  //         viewport: viewport
  //       };
  //       page.render(renderContext);
  //     });
  //   });
  // }

  _pdfPreview2(url: string){
    let f = document.createElement('iframe');
    f.src = 'assets/js/pdfjs/web/viewer.html?file=' + url;
    f.width = '752';
    f.height = '420';

    setTimeout(()=>{
      (document.getElementById('pdfpreview') as any).appendChild(f);
      
      this.nzSpinning = false;
    }, 0)
  }

  canvasWidth: any;
  canvasHeight: any;
  strokeColor: any;
  isMouseDown: any;
  lastLoc: any;
  lastTimestamp: any;
  lastLineWidth: any;
  canvas: any;
  context: any;
  nameData: any;
  isSign = false;
  _drawName(){
    this.canvasWidth = Math.min( 600 , 800 ); // $(window).width() - 20
    this.canvasHeight = this.canvasWidth;

    this.strokeColor = "black";
    this.isMouseDown = false;
    this.lastLoc = {x:0, y:0};
    this.lastTimestamp = 0;
    this.lastLineWidth = -1;

    this.canvas = document.getElementById("name-canvas");
    this.context = this.canvas.getContext("2d");

    this.canvas.width = this.canvasWidth;
    this.canvas.height = 320;

    let img = new Image();
    img.src = this.nameData;
    img.onload = () => {
      this.context.drawImage(img, 0, 0);
    }
    

    this.canvas.onmousedown = (e: any) => {
      e.preventDefault();
      this.beginStroke( {x: e.clientX , y: e.clientY} );
    };

    this.canvas.onmousemove = (e: any) => {
      e.preventDefault()
      if( this.isMouseDown ){
        this.moveStroke({x: e.clientX , y: e.clientY})
      }
    };

    this.canvas.onmouseup = (e: any) => {
      e.preventDefault()
      this.endStroke()
    };
    this.canvas.onmouseout = (e: any) => {
      e.preventDefault()
      this.endStroke()
    };

  }

  beginStroke(point: any){
    this.isMouseDown = true
    this.lastLoc = this.windowToCanvas(point.x, point.y);
    this.lastTimestamp = new Date().getTime();
  }
  moveStroke(point: any){
    var curLoc = this.windowToCanvas( point.x , point.y );
    var curTimestamp = new Date().getTime();
    // var s = this.calcDistance( curLoc , this.lastLoc )
    // var t = curTimestamp - this.lastTimestamp

    // var lineWidth = this.calcLineWidth( t , s );

    //draw
    this.context.beginPath();
    this.context.moveTo( this.lastLoc.x , this.lastLoc.y );
    this.context.lineTo( curLoc.x , curLoc.y );

    this.context.strokeStyle = this.strokeColor
    this.context.lineWidth = 8
    this.context.lineCap = "round"
    this.context.lineJoin = "round"
    this.context.stroke()

    this.lastLoc = curLoc
    this.lastTimestamp = curTimestamp
    this.lastLineWidth = 8

    this.isSign = true;
  }

  windowToCanvas( x: any , y: any ){
    var bbox = this.canvas.getBoundingClientRect();
    return {x:Math.round(x-bbox.left) , y:Math.round(y-bbox.top)}
  }
  calcDistance( loc1: any , loc2: any ){
    return Math.sqrt( (loc1.x - loc2.x)*(loc1.x - loc2.x) + (loc1.y - loc2.y)*(loc1.y - loc2.y) )
  }

  maxLineWidth = 30;
  minLineWidth = 1;
  maxStrokeV = 10;
  minStrokeV = 0.1;
  calcLineWidth( t: any , s: any ){

    var v = s / t;

    var resultLineWidth;
    if( v <= this.minStrokeV )
        resultLineWidth = this.maxLineWidth;
    else if ( v >= this.maxStrokeV )
        resultLineWidth = this.minLineWidth;
    else{
        resultLineWidth = this.maxLineWidth - (v-this.minStrokeV)/(this.maxStrokeV-this.minStrokeV)*(this.maxLineWidth-this.minLineWidth);
    }

    if( this.lastLineWidth == -1 )
        return resultLineWidth;

    return resultLineWidth*1/3 + this.lastLineWidth*2/3;
  }

  endStroke(){
    this.isMouseDown = false
  }

  clearName(){
    this.context.clearRect( 0 , 0 , this.canvasWidth, this.canvasHeight );
    this.nameData = null;
    this.isSign = false;
  }
  saveName(){
    if(this.isSign){
      this.nameData = this.canvas.toDataURL();

      this.signModalVisible = false;
      this.modalIsVisible = true;
      this.nzSpinning = true;

      // TODOs: 待测试
      this._pdfjs(this._getFormData());
      // this.util.success('保存成功');
    }else{
      // this.util.error('请先签名');
    }
  }

  signModalVisible = false;
  signModal(){
    if(this.pageType === 0){
      // this.util.info('预览不支持签署');
      return ;
    }
    this.modalIsVisible = false;
    this.signModalVisible = true;
    setTimeout(() => {
      this._drawName();
    }, 0)
  }
  signModalCancel(){
    this.signModalVisible = false;
  }
  signModalOk(){
    
  }

}

